//
//  EditchildInfoViewController.m
//  LoveDraw
//
//  Created by 零零壹 on 2017/8/29.
//  Copyright © 2017年 梁晨. All rights reserved.
//

#import "EditchildInfoViewController.h"
#import "EditchildInfoTableViewCell.h"
#import "DatePickerView.h"
#import "NSDate+Extension.h"


@interface EditchildInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong)UITableView *listV;
@property(nonatomic,strong)UIImagePickerController *pickerVC; // 照片选择器
@property(nonatomic,strong)NSString *HeadUrl;
@property(nonatomic,strong)UIImageView *HeadUrlimageV;

@end

@implementation EditchildInfoViewController


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


-(UITableView *)listV
{
    if (!_listV)
    {
        _listV = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KscreenW, KscreenH) style:(UITableViewStyleGrouped)];
        _listV.delegate= self;
        _listV.dataSource =self;
        _listV.estimatedSectionHeaderHeight = 0;
        _listV.estimatedSectionFooterHeight = 0;
        _listV.backgroundColor = [UIColor whiteColor];
        [_listV registerNib:[UINib nibWithNibName:@"EditchildInfoTableViewCell" bundle:nil] forCellReuseIdentifier:@"EditchildInfoTableViewCell"];
    }
    return _listV;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"修改信息";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.listV];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 150;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 120;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KscreenW, 120)];
    UIButton *commitBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    commitBtn.backgroundColor  = UIColors(0xF4760E);
    [commitBtn setTitle:@"提交" forState:(UIControlStateNormal)];
    [commitBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [footV addSubview:commitBtn];
    [commitBtn addTarget:self action:@selector(CommitAct) forControlEvents:(UIControlEventTouchUpInside)];
    commitBtn.layer.cornerRadius = 5;
    commitBtn.layer.masksToBounds = YES;
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footV.mas_left).offset(15);
        make.height.mas_equalTo(45);
        make.centerX.equalTo(footV.mas_centerX);
        make.centerY.equalTo(footV.mas_centerY);
    }];

    return footV;
}

-(void)CommitAct
{
    UITextField *nicknameTF = [self.view viewWithTag:10];
    UITextField *birthdayTF = [self.view viewWithTag:11];
    UITextField *addressTF = [self.view viewWithTag:12];
    UITextField *specialmanTF = [self.view viewWithTag:13];
    UITextField *specialtelTF = [self.view viewWithTag:14];


    NSMutableDictionary *RequestDic = [NSMutableDictionary dictionary];
    [RequestDic setValue:self.sid forKey:@"sid"];
    [RequestDic setValue:self.HeadUrl forKey:@"lifethumb"];
    [RequestDic setValue:nicknameTF.text forKey:@"nickname"];
    [RequestDic setValue:birthdayTF.text forKey:@"birthday"];
    [RequestDic setValue:addressTF.text forKey:@"address"];
    [RequestDic setValue:specialmanTF.text forKey:@"specialman"];
    [RequestDic setValue:specialtelTF.text forKey:@"specialtel"];



    [RequestManager HudRequestWithUrl:@"/index.php?g=App&m=StudentInfo&a=editStudent" parmDic:RequestDic requestType:RequestPOST view:self.view Success:^(id data)
    {
        [self.navigationController popViewControllerAnimated:YES];
    } error:^(NSError *error) {

    }];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KscreenW, 70)];
    headV.backgroundColor = [UIColor whiteColor];
    self.HeadUrlimageV = [[UIImageView alloc]initWithFrame:CGRectMake(KscreenW/2-60, 15, 120, 120)];
    self.HeadUrlimageV.backgroundColor = [UIColor redColor];
    self.HeadUrlimageV.userInteractionEnabled = YES;
    UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageTapAct:)];
    [self.HeadUrlimageV addGestureRecognizer:imageTap];
    [self.HeadUrlimageV sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KUrl,self.model.lifethumb]] completed:nil];

    self.HeadUrlimageV.layer.cornerRadius = 60;
    self.HeadUrlimageV.layer.masksToBounds = YES;
    self.HeadUrlimageV.layer.borderColor = UIColors(0xDFDFDF).CGColor;
    self.HeadUrlimageV.layer.borderWidth = 1;

    [headV addSubview:self.HeadUrlimageV];
    return headV;
}

-(void)imageTapAct:(UITapGestureRecognizer *)tap
{
    UIAlertController *imagechangeAc = [UIAlertController alertControllerWithTitle:@"更改头像" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"从手机相册选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action)
                            {
                                self.pickerVC = [[UIImagePickerController alloc]init];
                                self.pickerVC.delegate = self;
                                self.pickerVC.allowsEditing = YES;
                                self.pickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                                self.pickerVC.navigationBar.barTintColor = UIColors(0xF4760E);
                                [self presentViewController:self.pickerVC animated:YES completion:nil];
                            }];

    UIAlertAction *takePhoto = [UIAlertAction actionWithTitle:@"打开相机拍一张" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        self.pickerVC = [[UIImagePickerController alloc]init];
        self.pickerVC.delegate = self;
        self.pickerVC.allowsEditing = YES;
        self.pickerVC.navigationBar.barTintColor = UIColors(0xF4760E);
        self.pickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self.pickerVC animated:YES completion:nil];
    }];

    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:nil];
    [imagechangeAc addAction:album];
    [imagechangeAc addAction:takePhoto];
    [imagechangeAc addAction:cancel];
    [self presentViewController:imagechangeAc animated:YES completion:nil];

}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = info[@"UIImagePickerControllerEditedImage"];
    [[UploadImage sharedClient]doUploadImage:@"/index.php?g=App&m=Index&a=uploadsImgone" parameters:@{@"uid":[[NSUserDefaults standardUserDefaults]objectForKey:kUserId],@"access_token":[[NSUserDefaults standardUserDefaults]objectForKey:kAccessToken]} image:image successBlock:^(id responseBody)
     {
         NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseBody options:0 error:nil];
         [HUD showText:jsonDic[@"msg"] AfterTime:1];
         if ([jsonDic[@"flag"]isEqualToString:@"Success"])
         {
             self.HeadUrlimageV.image = info[@"UIImagePickerControllerEditedImage"];
             self.HeadUrl = jsonDic[@"data"];
         }
     } failureBlock:^(NSString *error)
     {

     }];
    [picker dismissViewControllerAnimated:YES completion:nil];
}




// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EditchildInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EditchildInfoTableViewCell" forIndexPath:indexPath];
    if (indexPath.row == 0)
    {
        cell.title.text = @"学生小名";
        cell.editTF.placeholder = @"请输入学生小名";
        cell.editTF.text = self.model.nickname;
    }else if (indexPath.row == 1)
    {
        cell.title.text = @"生日日期";
        cell.editTF.placeholder = @"请选择学生生日";
        cell.editTF.userInteractionEnabled = NO;
        cell.editTF.text = self.model.birthday;
    }else if (indexPath.row == 2)
    {
        cell.title.text = @"住址";
        cell.editTF.placeholder = @"请输入家庭住址";
        cell.editTF.text = self.model.address;
    }else if (indexPath.row == 3)
    {
        cell.title.text = @"紧急联系人";
        cell.editTF.placeholder = @"请输入紧急联系人姓名";
        cell.editTF.text = self.model.specialman;
    }else if (indexPath.row == 4)
    {
        cell.title.text = @"紧急联系电话";
        cell.editTF.placeholder = @"请输入紧急联系人电话";
        cell.editTF.text = self.model.specialtel;
    }
    cell.editTF.tag = indexPath.row+10;
    cell.selectionStyle = 0;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1)
    {
        EditchildInfoTableViewCell *cell = [self.listV cellForRowAtIndexPath:indexPath];
        if (cell.editTF.text.length != 0)
        {

        }else
        {
            [self showDate:indexPath];
        }
    }
}


-(void)showDate:(NSIndexPath *)indexPath
{
    DatePickerView *datepicker = [[DatePickerView alloc]initWithCompleteBlock:^(NSDate *selectDate)
    {

        EditchildInfoTableViewCell *cell = [self.listV cellForRowAtIndexPath:indexPath];
        cell.editTF.text =   [selectDate stringWithFormat:@"yyyy-MM-dd"];

//        [self.CalendarView reloadCalendarViewWithDate:[selectDate stringWithFormat:@"yyyy-MM-dd"]];
//        [_dateLabel setText:[selectDate stringWithFormat:@"yyyy年MM月"]];
//
//        self.year = [selectDate stringWithFormat:@"yyyy"];
//
//        self.month = [selectDate stringWithFormat:@"MM"];
//
//        [self initTimetableHttp];

    }];
    datepicker.themeColor = [UIColor blueColor];
    datepicker.datePickerStyle = DateStyleShowYearMonthDay;
    datepicker.dateType     = DateTypeStartDate;
    datepicker.title        = @"选择年月";
    datepicker.themeColor   = UIColors(MainColor);
    datepicker.minLimitDate = [NSDate date:@"2000-01-01" WithFormat:@"yyyy-MM-dd"];
    datepicker.maxLimitDate = [NSDate date:@"2025-01-01" WithFormat:@"yyyy-MM-dd"];
    [datepicker show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
